import tkinter as tk
from tkinter import filedialog, messagebox
import threading
import os
from separate import separate

class AudioSeparatorGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("音频分离工具")
        self.root.geometry("500x300")
        self.root.configure(bg="#f0f0f0")

        self.input_path = ""
        self.output_dir = ""

        self.create_widgets()

    def create_widgets(self):
        # 输入文件选择
        self.input_label = tk.Label(self.root, text="选择音频文件:", bg="#f0f0f0", fg="#333")
        self.input_label.pack(pady=10)

        self.input_entry = tk.Entry(self.root, width=50)
        self.input_entry.pack(pady=5)

        self.input_button = tk.Button(self.root, text="浏览", command=self.select_input_file, bg="#4CAF50", fg="white")
        self.input_button.pack(pady=5)

        # 输出目录选择
        self.output_label = tk.Label(self.root, text="选择输出目录:", bg="#f0f0f0", fg="#333")
        self.output_label.pack(pady=10)

        self.output_entry = tk.Entry(self.root, width=50)
        self.output_entry.pack(pady=5)

        self.output_button = tk.Button(self.root, text="浏览", command=self.select_output_directory, bg="#4CAF50", fg="white")
        self.output_button.pack(pady=5)

        # 开始按钮
        self.start_button = tk.Button(self.root, text="开始分离", command=self.start_separation, bg="#2196F3", fg="white")
        self.start_button.pack(pady=20)

        # 进度条
        self.progress_label = tk.Label(self.root, text="进度: 0%", bg="#f0f0f0", fg="#333")
        self.progress_label.pack(pady=10)

    def select_input_file(self):
        self.input_path = filedialog.askopenfilename(filetypes=[("音频文件", "*.wav;*.mp3")])
        self.input_entry.delete(0, tk.END)
        self.input_entry.insert(0, self.input_path)

    def select_output_directory(self):
        self.output_dir = filedialog.askdirectory()
        self.output_entry.delete(0, tk.END)
        self.output_entry.insert(0, self.output_dir)

    def update_progress(self, progress):
        self.progress_label.config(text=f"进度: {progress}%")

    def start_separation(self):
        if not self.input_path or not self.output_dir:
            messagebox.showerror("错误", "请选择输入文件和输出目录")
            return

        # 在新线程中运行分离过程，以避免阻塞 GUI
        thread = threading.Thread(target=self.run_separation)
        thread.start()

    def run_separation(self):
        try:
            # 这里调用你的分离函数，并传入用户选择的路径
            separate(self.input_path, self.output_dir)
            messagebox.showinfo("完成", "音频分离完成！")
        except Exception as e:
            messagebox.showerror("错误", f"分离过程中发生错误: {str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = AudioSeparatorGUI(root)
    root.mainloop()